import CommonModal from '@/components/CommonModal';
import Typography from '@/pages/OrderModule/common/components/Typography';
import SubTitle from "@/pages/OrderModule/common/components/SubTitle";
import { useEffect, useMemo, useState } from 'react';
import { find } from 'lodash';
import { Alert, message, Checkbox, Form, InputNumber, Modal, Popover } from 'antd';
import Api from '../../utils/service';
import styles from './index.module.less';
import { QuestionCircleOutlined } from '@ant-design/icons';

/** 批量发货 */
function BatchShip(props) {
	const { selectKeys, item, orderList, handleOk, handleCancel } = props;
	const [isOk, setIsOk] = useState(false);
	const [loading, setLoading] = useState(false);
	const [form] = Form.useForm();
	const [open, setOpen] = useState(false);
	const { updatePageConfig } = item;
	const [deliverList, setDeliverList] = useState([]);

	//可发货数量
	const countOrderNum = useMemo(() => {
		let count = 0;
		let count1 = 0;
		selectKeys.map(v => {
			const obj = find(orderList, ['id', v]);
			const logisticInfo = obj.logisticsList[0] || {};
			if (logisticInfo.logisticsNo && logisticInfo.logisticsCompanyId) {
				count = count + 1;
				if (obj.printState == 0) {
					count1 = count1 + 1;
				}
			}
		})
		return {
			canShipNum: count,
			unPrintNum: count1
		};
	}, [])

	useEffect(() => {
		setOpen(true);
	}, [])

	const onOk = async () => {
		if (countOrderNum.canShipNum == 0) {
			message.info('无可发货的订单');
			return;
		}
		form.validateFields().then(async val => {
			START_LOADING();
			//保存用户习惯-是否读取订单重量
			updatePageConfig('isExistWeight', val.isExistWeight);
			const { success, data } = await Api.batchOrderShip({
				orderIds: selectKeys,
				isExistWeight: val.isExistWeight ? 1 : 0,
				force: val.force ? true : false,
				orderWeight: val.orderWeight,
			})
			END_LOADING()
			if (success) {
				Modal.info({
					title: '操作提示',
					content: (
						<div>
							<p>成功数：<span className="common-color10">{data.successNum}</span>，失败数：<span className="common-color9">{data.failNum}</span></p>
							{data.failNum > 0 && <p>失败原因可能是:{data.errorMsg.join()},<br />具体请看每个订单的订单日志</p>}
						</div>
					),
					onOk() {
						setIsOk(true);
						setOpen(false);
					},
				});
			}
		}).catch(err => {
			console.log(err, 'err');
		})
	}

	const onCancel = () => {
		setOpen(false);
	}

	const afterClose = () => {
		if (isOk) {
			handleOk(2)
		} else {
			handleCancel();
		}
	}

	const isExistWeight = Form.useWatch('isExistWeight', form);

	return (
		<CommonModal
			title="批量发货"
			afterClose={afterClose}
			open={open}
			width="520px"
			onOk={onOk}
			onCancel={onCancel}
		>
			<Alert style={{ marginBottom: '12px' }} description="可发货订单数：即有快递和运单号的订单；无快递、无运单号、代发订单，将不会统计在内" />
			<SubTitle title="订单范围" as="s3" wrapStyle={{ marginBottom: '16px' }} symbol />
			<div style={{ color: '#333' }}>
				<div >
					<span style={{ marginLeft: '12px' }}>可发货订单数：</span><Typography type="error">{countOrderNum.canShipNum}</Typography>
				</div>
				<div style={{ margin: '12px 0' }}>
					<span>其中未打印订单：</span><Typography type="error">{countOrderNum.unPrintNum}</Typography>
					{countOrderNum.unPrintNum > 0 && <span style={{ color: 'green', marginLeft: '8px' }}>(请确认是否不打印就操作发货)</span>}
				</div>
			</div>
			<Form
				name="batchShip-modal-form"
				form={form}
				labelCol={{ span: 6 }}
				wrapperCol={{ span: 18 }}
				initialValues={{ isExistWeight: item.isExistWeight }}
				autoComplete="off"
			>
				<Form.Item
					label="订单重量"
					name="orderWeight"
					rules={isExistWeight ? null : [
						{
							required: true,
							message: '请输入订单重量!',
						},
					]}
				>
					<InputNumber className={styles.orderWeight} min={0} disabled={isExistWeight} controls={false} precision={3} max={999999} addonAfter="kg" />
				</Form.Item>
				<Form.Item
					label=" "
					colon={false}
					name="isExistWeight"
					valuePropName="checked"
					extra="（注：优先取订单实际称重重量，再取预估重量）"
				>
					<Checkbox onChange={() => form.setFieldsValue({ orderWeight: undefined })}>读取订单已有重量</Checkbox>
				</Form.Item>
				<SubTitle title="强制发货" as="s3" wrapStyle={{ marginBottom: '12px' }} symbol />
				<Form.Item name="force" valuePropName="checked" extra={<div>待拿货的商品，将直接<span className='common-color9'>转库存</span>发货</div>} label="是否强制发货">
					<Checkbox>
						强制发货
						<Popover
						content={
							<span style={{ display: "block", width: "186px" }}>
								<span style={{ fontWeight: 600 }}>不勾选强制发货：</span>
									则如果订单存在“未拿货”商品，将会发货失败，记录日志
							</span>
						}
					>
						<QuestionCircleOutlined style={{ color: "#999", cursor:'pointer', fontSize:'14px', marginLeft: '4px' }} />
					</Popover>
					</Checkbox>
				</Form.Item>
			</Form>
		</CommonModal>
	);
}

export default BatchShip;
